package com.example.demo.controller;

import com.example.demo.entity.BaseResponse;
import com.example.demo.entity.DeviceEntity;
import com.example.demo.entity.ResultBody;
import com.example.demo.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class DeviceController {
    @Autowired
    DeviceService deviceService;

    @RequestMapping("/getDevice")
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public DeviceEntity getDevice(int id) {
        return new DeviceEntity();
    }

    @RequestMapping("/saveDevice")
    @ResponseBody
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public ResultBody saveDevice(DeviceEntity device) {
        System.out.println(device.toString());
        if (deviceService.saveDevice(device)) {
            return new ResultBody(0, "success");
        } else {
            System.out.println("失败");
            return new ResultBody(1, "fail");
        }
    }

    @RequestMapping("/delDevice")
    @ResponseBody
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public ResultBody delDevice(int id) {
        if (deviceService.delDevice(id)) {
            return new ResultBody(0, "success");
        } else {
            return new ResultBody(1, "fail");
        }
    }

    @RequestMapping("/listDevice")
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public BaseResponse<DeviceEntity> listDevice(DeviceEntity device) {
        device.setStart((device.getPage() - 1) * device.getLimit());
        List<DeviceEntity> deviceList = deviceService.findAll(device);
        int count = deviceService.getCount(device);
        return new BaseResponse<DeviceEntity>(0, "success",
                count, deviceList);
    }
}
